package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

public class SimpleRedisLock implements ILock {
    private String name; // 业务名称
    private StringRedisTemplate stringRedisTemplate;
    private static final String KEY_PREFIX = "lock:"; // 锁的前缀
    private static final String ID_PREFIX = UUID.randomUUID().toString(true) + "-"; // hutool生成一个随机的uuid并去掉横线
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;
    // 执行Lua脚本
    static {
        //UNLOCK_SCRIPT = new DefaultRedisScript<>("if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) else return 0 end", Long.class);
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }

    public SimpleRedisLock(String name, StringRedisTemplate stringRedisTemplate) {
        this.name = name;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * 尝试获取锁
     *
     * @param timeoutSec : 锁持有的超时时间 ， 过期后自动释放 ;
     * @return true代表获取锁成功 ， false代表获取锁失败 ;
     */
    @Override
    public boolean tryLock(long timeoutSec) {
        // 获取当前线程id :
        String threadId = ID_PREFIX + Thread.currentThread().getId();
        Boolean success = stringRedisTemplate.opsForValue()
                .setIfAbsent(KEY_PREFIX + name, threadId, timeoutSec, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(success);
    }

    /**
     * 释放锁
     */
    @Override
    public void unlock() {
        /*
        // ①互斥锁释放
        // 获取线程标识
        String threadId = ID_PREFIX + Thread.currentThread().getId() ;
        // 获取锁中的指示
        String id = stringRedisTemplate.opsForValue().get(KEY_PREFIX + name);
        // 判断是否一致
        if(threadId.equals(id)){
            // 释放锁
            stringRedisTemplate.delete(KEY_PREFIX + name);
        }*/
        // ②redis原子操作lua脚本，保证判断与删除的原子性，防止释放锁bug
        stringRedisTemplate.execute(
                UNLOCK_SCRIPT,
                Collections.singletonList(KEY_PREFIX + name),
                ID_PREFIX + Thread.currentThread().getId()
        );
    }
}